﻿


import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { isAllFieldsFilled, downloadfun, IgetDeptList, queryURLParams, dealTime, getBrowserInfo, getRecentYears, showDeleteConfirm, previewCom} from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const data = reactive({

        messageTest: "",
        proxy: "",
        popShow: false,
        textareaShow: false,
        textareaContent:null,
        settingList: [
        ],
        previewInfo: {
            pdfurl: "",
            pdfOpen: false,
            previewShow: false,
            imgUrl: ""
        },
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        levelList:[],
        uploadLock: false,
        formData: {
            SupplyName: null,
            LevelId: null,
            DepartmentId: null
        },
        deptList: [],
        typeList: [],

        urlinfo: {},
        userinfo: {

        },
        yearList: [],
       cIndex:0,

    })
    let params = toRefs(data)
    const methods = {
        getDeptList: () => {
            return new Promise(async (resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                resolve()

            })
        },
        typeChange: () => {
            methods.IGetEmergencyTeamTitle()
            params.settingList.value = []
        },
        handlePreview: (item) => {
            if (item.FileName.indexOf('.pdf') != -1) {
                params.previewInfo.value.pdfUrl = item.FilePath
                params.previewInfo.value.pdfOpen = true
            } else {
                params.previewInfo.value.imgUrl = item.FilePath
                params.previewInfo.value.previewShow = true
            }
        },
        ISaveAccidentItem: (item) => {
            showDeleteConfirm({
                title: '确定保存此信息?',
                content: '',
                okFun: () => methods.SaveAccidentItem(item)
            })
        },
        SaveAccidentItem: (e) => {
            
            delete e.Remark
            delete e.OtherType
            e.FileList = e.FileList.map(es => es.FileId)
            if (!isAllFieldsFilled(e)) {
                return params.messageTest.value.info('请检查信息填写是否完整')
            }
            if (e.FileList.length == 0) {
                return params.messageTest.value.info('请检查附件是否上传')
            }
            params.uploadLock.value = true
            Request({
                url: "/AccidentManagement/SaveAccidentItem",
                method: 'post',
                data: {
                    item: { ...e, FormId: params.urlinfo.value.id},
          
                }
            }).then(res => {
                params.messageTest.value.info(res.Msg)
                methods.IGetAccidentDetail()
            }).finally(() => {
                params.uploadLock.value = false
            })
        },
        downLoad: (FileName, FilePath) => {
            params.uploadLock.value = true
            downloadfun(FileName, FilePath).finally(() => {
                params.uploadLock.value = false
            })
        },
        IGetAccidentTypeList: () => {
            return new Promise((resolve, rej) => {
                params.uploadLock.value = true
                Request({
                    url: "/AccidentManagement/GetAccidentTypeList",
                    method: 'post',
                }).then(res => {
                    console.log(res, 'res')
                    params.typeList.value = res.Data.map(e => ({
                        label: e.ConfigValue,
                        value: e.Id
                    }));
                    resolve()
                }).finally(() => {
                    params.uploadLock.value = false
                })
            })
        },
        handleOk: () => {
            params.settingList.value[params.cIndex.value].Description = params.textareaContent.value
            params.textareaShow.value = false
        },
        handleoptextarea: (index) => {
            if (params.settingList.value[index] && params.settingList.value[index]?.Description) {
                params.textareaContent.value = params.settingList.value[index].Description
            } else {
                params.textareaContent.value=null
            }
            params.cIndex.value = index
            params.textareaShow.value=true
        },
        ITeamType: () => {
            return new Promise((resolve, rej) => {
                params.uploadLock.value = true
                Request({
                    url: "/EmergencyPlan/GetEmergencyTeamType",
                    method: 'post',
                    data: {
                        type: params.urlinfo.value.type != 9 ? "Add" :"view"
                    }
                }).then(res => {
                    params.levelList.value = res.Data.map(e => ({
                        label: e.ConfigValue,
                        value: e.Id
                    }))
                    methods.IGetEmergencyTeamTitle()
                    resolve()
                }).finally(() => {
                    params.uploadLock.value = false
                })
            })
        },
        addConfig: () => {
            let obj = {
                DepartmentId: params.userinfo.value.DepartmentId
            }
            params.settingList.value.push(obj)
        },
        handleDownloadTemplate: () => {
            params.uploadLock.value = true
            downloadfun('应急队伍模板', '../../File/Templete/EmergencyTeam/导入应急队伍.xls').then(() => {
            }).finally(() => {
                params.uploadLock.value = false
            })
        },
        handleBeforeUpload: () => {
            if (!params.formData.value.TypeId) {
                params.messageTest.value.info("请先选择级别")
                return false
            }
        },
        handleImport: (info) => {

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('file', info.file.originFileObj)
                formData.append('TypeId', params.formData.value.TypeId)
                formData.append('DepartmentId', params.formData.value.DepartmentId)
                Request({
                    url: `/EmergencyPlan/ImportEmergencyTeam`,
                    method: 'post',
                    data: formData
                }).then(res => {

           
                    params.settingList.value = [
                        ...params.settingList.value,
                        ...res.Data
                    ]

                    params.uploadLock.value = false


                })

            }
        },
        handleChange: (info,index) => {

            let subarrys = info.fileList.filter(e => !e.old).map(e => e.originFileObj)

            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                for (let e of subarrys) {
                    formData.append('file', e)
                }

                Request({
                    url: `/download/uploadfile?Path=Accident`,
                    method: 'post',
                    data: formData
                }).then(res => {
                    params.settingList.value[index].FileList = params.settingList.value[index] && params.settingList.value[index].FileList?.length>0? [
                        ...res.Data.map(e => {
                            const { FilePath, FileName } = e
                            e.url = FilePath
                            e.name = FileName
                            return e
                        }),
                      ...params.settingList.value[index].FileList.filter(e => e.FileId)
                    ] : [...res.Data.map(e => {
                        const { FilePath, FileName } = e
                        e.url = FilePath
                        e.name = FileName
                        return e
                    })]


                    params.uploadLock.value = false
                })

            }
        },
        IdelConfig: (index, item) => {
            showDeleteConfirm({
                title: `提示：事故名称【${item.Responsible}}】，删除后将无法恢复，请您确认。`,
                content: '',
                okFun: () => methods.delConfig(index, item)
            })
        },
        delConfig: (index,item) => {
            if (item.Id) {
                params.uploadLock.value = true
                Request({
                    url: "/AccidentManagement/DeleteAccidentItem",
                    method: 'post',
                    data: {
                        Id: item.Id
                    }
                }).then(() => {
                    params.settingList.value = params.settingList.value.filter((_e, i) => i != index)
                }).finally(() => {
                    params.uploadLock.value = false
                })
            } else {
                params.settingList.value = params.settingList.value.filter((_e, i) => i != index)
            }
          
        },
        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },

        IGetAccidentDetail: () => {
            return new Promise((resolve, rej) => {
                params.uploadLock.value = true
                Request({
                    url: "/AccidentManagement/GetAccidentDetail",
                    method: 'post',
                    data: {
                        Id: params.urlinfo.value.id
                    }
                }).then(res => {
                    params.formData.value = res.Data
                    params.formData.value.user = `${res.Data.CreateUserName}(${res.Data.UpdateUser})`
                    params.formData.value.time = dealTime(res.Data.UpdateTime, 'YYYY-MM-DD HH:mm')
                    params.settingList.value = res.Data.ItemList.map(e => {
                        e.CloseTime = dayjs(dealTime(e.CloseTime, 'YYYY-MM-DD HH:mm'))
                        e.AccidentDate = dayjs(dealTime(e.AccidentDate, 'YYYY-MM-DD HH:mm'))
                        e.FileList=e.FileList.map(es => {
                            es.old = true
                            return es
                        })
                        return e
                    })
                    console.log(params.settingList.value,'  params.settingList.value ')
                    params.uploadLock.value = false
                    resolve()

                })
            })

        },

        handleAddData: (data) => {
            params.uploadLock.value = true
            if (params.urlinfo.value.type == 1) {
                Request({
                    url: "/AccidentManagement/EditAccidentForm",
                    method: 'post',
                    data: data
                }).then(res => {
                    if (res.Code == 100) {
                        params.messageTest.value.info(res.Msg)
                        setTimeout(() => {
                            methods.onBack()
                        }, 1000)

                    }
                }).finally(() => {
                    params.uploadLock.value = false
                })
            } else {
                Request({
                    url: "/AccidentManagement/AddAccidentForm",
                    method: 'post',
                    data: data
                }).then(res => {
                    if (res.Code == 100) {
                        params.messageTest.value.info(res.Msg)
                        setTimeout(() => {
                            methods.onBack()
                        }, 1000)

                    }
                }).finally(() => {
                    params.uploadLock.value = false
                })
            }




        },

        IDeleteFile: (item) => {
            params.uploadLock.value = true
        Request({
            url: "/AccidentManagement/DeleteFile",
            method: 'post',
            data: {
                FileId: item.FileId
            }
        }).then(res => {
            if (res.Code == 100) {
                methods.IGetAccidentDetail()
                params.messageTest.value.info(res.Msg)
            }
        }).finally(() => {
            params.uploadLock.value = false
        })
   
    },
        deletefile: (e) => {
            showDeleteConfirm({
                title: '确定删除所选文件?',
                content: '',
                okFun: () => methods.IDeleteFile(e)
            })
        },
        onSubmit() {
            let obj = {
                model: {
                    ...params.formData.value,
                    Id: params.urlinfo.value.id
                },
                items: params.settingList.value.map(e => {
                    e.FileList = e.FileList?.filter(es=>!es.old).map(es => es.FileId)
                    return e
                })
            }
            //if (!isArrayObjectsAllFilled(obj.items)) {
            //    return params.messageTest.value.info('请检查信息填写是否完整')
            //}
            
                methods.handleAddData(obj)
       
        },

        onBack: () => {
            window.location.href = '/AccidentManagement/AMList'
        },
        IGetEmergencyTeamTitle: () => {
            Request({
                url: "/EmergencyPlan/GetEmergencyTeamTitle",
                method: 'post',
                data: {
                    TypeId: params.formData.value.TypeId
                }
            }).then(res => {
                if (res.Code == 100) {

                }
            }).finally(() => {
                params.uploadLock.value = false
            })
        },
        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            params.urlinfo.value = queryURLParams()

            let info = Storage.get('AccountInfo', true)
            params.userinfo.value = info
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(async res => {
                Storage.set('token', res.Data, true)
          
      
                params.yearList.value = getRecentYears()
                params.formData.value.Years = dayjs().format('YYYY')
                if (params.urlinfo.value.type) {
                    await methods.IGetAccidentDetail()
                    await methods.getDeptList()
                    await methods.IGetAccidentTypeList()


                }
                 else {
                    await methods.getDeptList()
                    await methods.IGetAccidentTypeList()
                    params.formData.value.user = `${info.UserName}(${info.UserNo})`
                    params.formData.value.time = dayjs().format('YYYY-MM-DD HH:mm')
                    params.formData.value.DepartmentId = info.DepartmentId
                }



            })

            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

        },

    }
    const template = {
        imageModel: previewCom(params, methods).imageModel,
        pdfPopModel: previewCom(params, methods).pdfPopModel,


        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>

  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(0)"
  >
          <a-button  :loading="uploadLock"  v-if="urlinfo.type!=9&&userinfo.DepartmentId==20" type="primary">保存</a-button>
  </a-popconfirm>

                       
              
                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition